<template>
  <view class="masklayer" :style="my_style">
    <view class="header df fdc alc">
      <image :src="info.logo"></image>
      <text>{{ info.name }}</text>
    </view>
    <view class="content">
      <view>该程序将获取您的以下权限</view>
      <text>获取您的信息（头像，昵称信息等）</text>
    </view>
    <view class="btn-box flex-between">
      <view class="cancel-btn" @tap="goBack">拒绝</view>
      <button
        class="bottom font-32"
        v-if="!can_use"
        type="primary"
        open-type="getUserInfo"
        lang="zh_CN"
        @getuserinfo="getUserInfo"
      >
        同意
      </button>
      <button class="bottom font-32" v-if="can_use" type="primary" @click="getUserProfile">
        同意
      </button>
    </view>
  </view>
</template>

<script>
  export default {
    data() {
      return {
        info: {},
        code: '',
        authorize_message: '',
        share_user_id: '',
        can_use: false, // 是否可用
      }
    },
    onLoad() {
      this.canUse()
      this.getCode()
      this.copyright()
      this.share_user_id = uni.getStorageSync('share_user_id') || ''
    },
    methods: {
      canUse() {
        if (uni.getUserProfile) {
          this.can_use = true
        }
      },
      async copyright() {
        const res = await this.$api.common.system('copyright')
        if (res.code === 200) {
          this.info = res.data
        }
      },
      // 获取code
      getCode() {
        let _this = this
        uni.login({
          success(res) {
            if (res.errMsg == 'login:ok') {
              _this.code = res.code
            }
          },
        })
      },
      getUserProfile(e) {
        // 推荐使用wx.getUserProfile获取用户信息，开发者每次通过该接口获取用户个人信息均需用户确认
        // 开发者妥善保管用户快速填写的头像昵称，避免重复弹窗
        uni.getUserProfile({
          desc: '用于完善会员资料', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
          success: (res) => {
            this.authorize_message = res
            uni.showLoading({
              title: '登录中...',
            })
            this.login(() => {
              uni.hideLoading()
            })
          },
        })
      },
      getUserInfo(e) {
        let that = this
        if (e.detail.errMsg == 'getUserInfo:fail auth deny') {
          uni.showModal({
            title: '温馨提示',
            content: '您点击了拒绝授权，将无法进入小程序，请授权之后再进入!!!',
            showCancel: false,
            confirmText: '返回授权',
            success(res) {
              if (res.confirm) {
                console.log('用户点击了“返回授权”')
              }
            },
          })
          return
        }
        uni.showLoading({
          title: '登录中...',
        })
        this.checkAuthorize(() => {
          uni.hideLoading()
        })
      },
      // 检验是否授权
      checkAuthorize(fn) {
        let _this = this
        uni.getSetting({
          success: (res) => {
            console.log(res)
            if (res.errMsg == 'getSetting:ok') {
              uni.getUserProfile({
                success: (res) => {
                  console.log(res)
                  _this.authorize_message = res
                  _this.login(fn) // 执行登录
                },
              })
            } else {
              fn()
            }
          },
        })
      },
      // 用户登录-微信小程序授权
      async login(fn) {
        let code = this.code
        let { iv, encryptedData } = this.authorize_message
        let res = await this.$api.common.user('loginWithWeapp', {
          code,
          iv,
          encryptedData,
          nonce: this.randomStr(10),
          share_user_id: this.share_user_id,
        })
        if (res.code === 200) {
          const { access_token, client } = res.data
          uni.setStorageSync('access_token', access_token)
          uni.setStorageSync('member_id', client.member_id)
          this.$store.dispatch('getUserInfo')
          if (!client.mobile) {
            uni.redirectTo({
              url: '/views/auth/bind_phone',
            })
          } else {
            this.back()
          }
          fn()
        }
      },

      // 返回上一页
      back() {
        // 获取页面栈
        var pages = getCurrentPages()
        if (pages.length > 1) {
          // 上一个页面实例对象
          var prePage = pages[pages.length - 2]
          // 触发上个界面
        }
        this.goBack()
      },
    },
    onShow() {},
  }
</script>

<style lang="scss" scoped>
  /* 授权窗口 */

  .masklayer {
    display: flex;
    height: 100vh;
    background: #fff;
    flex-direction: column;
    align-items: center;
  }

  .header {
    width: 650rpx;
    height: 360rpx;
    padding-top: 94rpx;
    padding-bottom: 48rpx;
    margin-bottom: 48rpx;
    font-size: 40rpx;
    line-height: 56rpx;
    text-align: center;
    border-bottom: 1px solid #ccc;
  }

  .header image {
    width: 148rpx;
    height: 148rpx;
    margin-bottom: 14rpx;
    border-radius: 8rpx;
  }

  .content {
    margin-bottom: 92rpx;
    margin-left: 50rpx;
    font-size: 32rpx;
    line-height: 44rpx;
    text-align: center;
  }

  .content text {
    display: block;
    margin-top: 40rpx;
    font-size: 28rpx;
    line-height: 40rpx;
    color: #666;
  }

  /* 按钮 */

  .btn-box {
    width: 100%;
    padding: 0 64rpx;
    font-size: 32rpx;
    text-align: center;
    box-sizing: border-box;
  }

  .cancel-btn {
    width: 280rpx;
    height: 92rpx;
    line-height: 92rpx;
    color: var(--color);
    border: 2rpx solid var(--color);
    border-radius: 8rpx;
  }

  .bottom {
    width: 280rpx !important;
    height: 92rpx !important;
    padding: 0 0;
    margin: 0 !important;
    font-weight: 400;
    line-height: 92rpx !important;
    background: var(--color);
    border-radius: 8rpx;
  }
</style>
